package srv

import (
	"background/model/back/entity"
	"background/model/back/entity/extrax"
	"background/model/back/repo"
	"context"
	"log"
	"time"
)

func (r CloudUser) Info(ctx context.Context, id int64) (*entity.CloudUser, error) {
	first, err := r.db.CloudUser.WithContext(ctx).Where(repo.CloudUser.ID.Eq(id)).First()
	if err != nil {
		return nil, err
	}
	return first, nil
}
func (r CloudUser) Plan(ctx context.Context, u *entity.CloudUser) (*entity.CloudPlan, error) {
	first, err := r.db.CloudPlan.WithContext(ctx).Where(repo.CloudPlan.ID.Eq(u.PlanID)).First()
	if err != nil {
		return nil, err
	}
	return first, nil
}
func (r CloudUser) Traffic(ctx context.Context, u int64) ([]*entity.CloudLogTraffic, error) {
	unix := time.Now().AddDate(0, -1, 0).Unix()
	find, err := r.db.CloudLogTraffic.WithContext(ctx).Order(
		repo.CloudLogTraffic.RecordAt,
	).Where(repo.CloudLogTraffic.UserID.Eq(u),
		repo.CloudLogTraffic.RecordAt.Gt(unix)).Find()
	if err != nil {
		return nil, err
	}
	return find, nil
}
func (r CloudUser) Order(ctx context.Context, u int64) ([]*entity.CloudOrder, error) {
	unix := time.Now().AddDate(0, -1, 0).Unix()
	log.Println(unix)
	find, err := r.db.CloudOrder.WithContext(ctx).Order(
		repo.CloudOrder.CreatedAt,
	).Where(repo.CloudOrder.UserID.Eq(u)).Find()
	if err != nil {
		return nil, err
	}
	return find, nil
}
func (r CloudUser) Subscribe(ctx context.Context, u int64) (extrax.Subscribe, error) {
	var subscribe extrax.Subscribe
	find, err := r.db.CloudUser.WithContext(ctx).Order(
		repo.CloudUser.CreatedAt,
	).Where(repo.CloudUser.ID.Eq(u)).First()
	if err != nil {
		return subscribe, err
	}
	subscribe = extrax.Subscribe{
		PlanID:         find.PlanID,
		Token:          "",
		ExpiredAt:      find.ExpiredAt.Unix(),
		U:              0,
		D:              0,
		TransferEnable: 0,
		Email:          find.Email,
		SubscribeUrl:   "",
		ResetDay:       find.ResetDay,
	}
	if find.PlanID != 0 {
		plan, err := r.db.CloudPlan.WithContext(ctx).Order(
			repo.CloudPlan.CreatedAt,
		).Where(repo.CloudPlan.ID.Eq(u)).First()
		if err != nil {
			return subscribe, err
		}
		subscribe.Plan = *plan
	}
	return subscribe, nil
}
